// -----------------------------
// Author: 		Dhaenens Gert	
// Creation: 	2/21/2015 7:40:03 PM				
// -----------------------------

#include "CThread.h"

#include "ThreadHandler.h"

namespace Flow
{

	UInt32 CThread::s_ThreadCount = 0;

	CThread::CThread()
		: m_lpAction(nullptr)
		, m_ThreadCompleted(NULL)
	{
		if (!ThreadHandler::IsInitialized())
			ThreadHandler::Initialize();
		++s_ThreadCount;
	}

	CThread::~CThread()
	{
		m_lpAction->Release();

		if (s_ThreadCount <= 1)
			ThreadHandler::Uninitialize();
		--s_ThreadCount;
	}

	void CThread::Release()
	{
		delete this;
	}

	void CThread::Start(ThreadProc fn, void* lpArgs)
	{
		m_Function = fn;
		m_Args = lpArgs;

		m_lpAction = ThreadHandler::RunASync(this);
	}
	void CThread::Stop()
	{
		// Not implemented at the moment
		ASSERT(false);
	}

	void CThread::WaitForExit()
	{
		WaitForSingleObjectEx(m_ThreadCompleted.Get(), INFINITE, FALSE);
	}

	Bool CThread::IsRunning() const
	{
		DWORD dwResult = WaitForSingleObjectEx(m_ThreadCompleted.Get(), 0, FALSE);
		if (dwResult == WAIT_TIMEOUT)
			return true;
		return false;
	}

}